<?php
declare (strict_types = 1);

namespace app\common\model;

use app\common\facade\Target;
use app\common\model\Statistics as StatisticsModel;

class Release extends Base
{
    protected $name = 'release';

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname');
    }
    protected function qUser()
    {
        return $this->hasOne(User::class, 'id', 'q_uid')->field('id,code,nickname');
    }

    //每日释放
    public static function release_award_day()
    {
        try {
            $list = Release::where(['is_capping'=>0,'type'=>1])->select();
            foreach ($list as $k=>$v){
                if($v->already+$v->once > $v->capping)
                {
                    $once = $v->capping - $v->already;
                    $v->is_capping = 1;
                }else{
                    $once = $v->once;
                }
                $v->already = $v->already+$once;
                $v->save();
                Target::Account()
                    ->basics($v->uid, 'bonus', $once, '推荐奖励', '+')
                    ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
                    ->createBonus($v->q_uid, '1');
                StatisticsModel::_update($once, 'expend');
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //每周释放
    public static function release_award_week()
    {
        try {
            $list = Release::where(['is_capping'=>0,'type'=>2])->select();
            foreach ($list as $k=>$v){
                if($v->already+$v->once > $v->capping)
                {
                    $once = $v->capping - $v->already;
                    $v->is_capping = 1;
                }else{
                    $once = $v->once;
                }
                $v->already = $v->already+$once;
                $v->save();
                Target::Account()
                    ->basics($v->uid, 'bonus', $once, '推荐奖励', '+')
                    ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
                    ->createBonus($v->q_uid, '1');
                StatisticsModel::_update($once, 'expend');
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
